package com.cndongtai.service.upload;

import java.io.IOException;
import java.util.Date;
import java.util.Random;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import com.cndongtai.constant.SystemConstant;
import com.cndongtai.constant.UserConstant;
import com.cndongtai.dao.impl.UploadDao;
import com.cndongtai.po.UploadFile;
import com.cndongtai.po.User;
import com.cndongtai.util.DateUtil;
import com.cndongtai.util.FileUtil;

@Service("uploadService")
public class UploadService {
	
	@Resource(name="uploadDao")
	private UploadDao uploadDao;

	public UploadFile uploadFile(HttpServletRequest request,MultipartFile file) {
		UploadFile upload = new UploadFile();
		
		String uploadTime = DateUtil.timeFormatyyyyMMddHHmmssSSSToday() + getRandom();//上传文件的时间
		
		if(file.isEmpty()){
//			logger.error("method:uploadFile, errorInfo: file is empty");
		}else{
			String fileName = file.getOriginalFilename();
			String newFileName = uploadTime+fileName.substring(fileName.lastIndexOf("."));
			// 原图存放路径
			String filePathSaveOriginal = SystemConstant.FILE_FIRMWARE_PATH+"/" + newFileName;
			String filePath = "/"+newFileName;
			try {
				upload.setFileName(newFileName);
				upload.setFilePath(filePath);
				upload.setUploadTime(new Date());
				User user = (User) request.getSession().getAttribute(UserConstant.SESSION_USER);
				if(null!=user){
					upload.setUploadBy(user.getUserId());
				}
				
				int isFlag = uploadDao.saveUploadFile(upload);
				if(isFlag>0){
					boolean saveResult = FileUtil.saveFile(filePathSaveOriginal,file.getBytes());
					if(!saveResult) {
						return null;
					}
				}
			} catch (IOException e) {
//				logger.error("method:uploadFile Exception Ocurred",e);
				return null;
			}
		}
		
		return upload;
	}
	
	public UploadFile uploadFileFromApp(String userId, MultipartFile file) {
		UploadFile upload = new UploadFile();
		
		String uploadTime = DateUtil.timeFormatyyyyMMddHHmmssSSSToday() + getRandom();//上传文件的时间
		
		if(file.isEmpty()){
//			logger.error("method:uploadFile, errorInfo: file is empty");
		}else{
			String fileName = file.getOriginalFilename();
			String newFileName = uploadTime+fileName.substring(fileName.lastIndexOf("."));
			// 原图存放路径
			String filePathSaveOriginal = SystemConstant.FILE_FIRMWARE_PATH+"/" + newFileName;
			String filePath = "/"+newFileName;
			try {
				upload.setFileName(newFileName);
				upload.setFilePath(filePath);
				upload.setUploadTime(new Date());
				upload.setUploadBy(Long.parseLong(userId));
				
				int isFlag = uploadDao.saveUploadFile(upload);
				if(isFlag>0){
					boolean saveResult = FileUtil.saveFile(filePathSaveOriginal,file.getBytes());
					if(!saveResult) {
						return null;
					}
				}
			} catch (IOException e) {
//				logger.error("method:uploadFile Exception Ocurred",e);
				return null;
			}
		}
		
		return upload;
	}
	
	public UploadFile queryUploadFileById(Long id) {
		return uploadDao.queryUploadFileById(id);
	}
	
	/**
	 * 生成文件名随机数
	 * @return
	 */
	public static final String getRandom() {
		Random random = new Random();
		
		StringBuffer randomBf = new StringBuffer();
		for(int i=0;i<4;i++) {
			randomBf.append(String.valueOf(random.nextInt(9)));
		}
		
		return randomBf.toString();
	}
}
